/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.upload.service.processor;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import info.peigen.hotpot.common.service.base.processor.Processor;
import info.peigen.hotpot.common.service.base.processor.ProcessorServiceContext;
import info.peigen.hotpot.component.upload.domain.UploadBatch;
import info.peigen.hotpot.component.upload.service.result.UploadResult;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.UploadedFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * <b>(UploadBatchTransferFileProcessor)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/11/14
 */
@Slf4j
@Component
public class UploadBatchTransferFileProcessor extends AbstractUploadServiceProcessor implements Processor {
    @Override
    public Integer level() {
        return 20;
    }

    @Override
    public void execute(ProcessorServiceContext serviceContext) {
        UploadBatch  uploadBatch = (UploadBatch) serviceContext.getDomain();
        UploadResult result      = (UploadResult) serviceContext.getResult();
        List<String> filesPath   = Lists.newArrayList();

        for (int i = 0; i < uploadBatch.getUploadedFileList().size(); i++) {
            UploadedFile uploadedFile = uploadBatch.getUploadedFileList().get(i);
            String       fileName     = uploadBatch.getFileNames().get(i);
            fileName = Optional.ofNullable(fileName).orElse(uploadedFile.getName());
            String filePath;
            if (ObjectUtil.isNotNull(uploadBatch.getUploadPath())) {
                if (!uploadBatch.getUploadPath().endsWith("/")) {
                    uploadBatch.setUploadPath(uploadBatch.getUploadPath() + "/");
                }
                filePath = uploadProperties.getUploadPath() + uploadBatch.getUploadPath() + fileName;
            } else {
                filePath = uploadProperties.getUploadPath() + fileName;
            }
            log.info(filePath);
            File file = new File(filePath);
            try {
                uploadedFile.transferTo(file);
            } catch (IOException e) {
                result.setFail("上传文件异常,文件路径:filePath=" + filePath);
                e.printStackTrace();
                return;
            }
        }
        result.setSuccess();
        result.setFilesPath(filesPath);
    }
}